//
//  XQIdentityController.m
//  JoinPeso
//
//  Created by 小琦 on 2024/11/23.
//

#import "XQIdentityController.h"
#import "XQCustomEngeLabel.h"
#import "XQIdentityPhotoView.h"
#import "XQIdentityErrorController.h"
#import "XQIdentityAccureWayController.h"

#import "XQIdentityBirthdayPopView.h"
#import "XQCustomOptionalPop.h"
#import "XQAccureIdentityInfoPop.h"

@interface XQIdentityController ()
@property (nonatomic,strong) UIView *mainView;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) XQCustomEngeLabel *topLabel;
@property (nonatomic,strong) XQIdentityPhotoView *photoView;
@property (nonatomic,strong) XQIdentityPhotoView *faceView;
@property (nonatomic,strong) XQButton *bottomButton;
@property (nonatomic, assign) NSInteger photoIndex;
@property (nonatomic,strong) UIImage *photoImage;
@property (nonatomic,strong) UIImage *faceImage;
@property (nonatomic,copy) NSArray *preferredDataSource; //首选
@property (nonatomic,copy) NSArray *alternativeDataSource;// 备选

@property (nonatomic,copy) NSString *selectName;
@property (nonatomic,copy) NSString *selectNumer;
@property (nonatomic,copy) NSString *selectBirthday;

@property (nonatomic,copy) NSString *maneuvers;

@end

@implementation XQIdentityController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self makeUI];
    [self makeConstraints];
    
    [self refreshData];
}

- (void)makeUI {
    self.view.backgroundColor = kCardColor;
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.mainView];
    [self.mainView addSubview:self.topLabel];
    [self.mainView addSubview:self.photoView];
    [self.mainView addSubview:self.faceView];
    [self.mainView addSubview:self.bottomButton];
}

- (void)makeConstraints {
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo([UIScreen mainScreen].topHeight);
        make.left.right.equalTo(@0);
        make.bottom.offset(-[UIScreen mainScreen].bottomHeight);
    }];
    [self.mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.mas_equalTo([UIScreen mainScreen].width);
    }];
    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(20);
        make.left.equalTo(@12);
        make.right.equalTo(@-12);
        make.height.mas_equalTo(94);
    }];
    [self.photoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topLabel.mas_bottom).offset(20);
        make.left.right.equalTo(@0);
    }];
    [self.faceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.photoView.mas_bottom).offset(20);
        make.left.right.equalTo(@0);
    }];
    [self.bottomButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.faceView.mas_bottom).offset(40);
        make.left.right.equalTo(@0);
        make.bottom.mas_equalTo(-20);
    }];
}

#pragma mark - setter

- (void)setTopTitle:(NSString *)topTitle {
    [self.navigationBar setTitle:topTitle];
}

#pragma mark - private

- (void)uploadClick:(NSInteger)index {
    
    self.photoIndex = index;
    if (index == 0) {
        XQIdentityAccureWayController *vc = [XQIdentityAccureWayController new];
        vc.isPhoto = YES;
        vc.topTitle = self.navigationBar.title;
        vc.preferredDataSource = self.preferredDataSource;
        vc.alternativeDataSource = self.alternativeDataSource;
        [self.navigationController pushViewController:vc animated:YES];
    }else {
        XQIdentityErrorController *vc = [XQIdentityErrorController new];
        vc.isPhoto = NO;
        vc.topTitle = self.navigationBar.title;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)bottomClick {
    if (!self.photoView.isCompleted) {
        [self uploadClick:0];
        return;
    }
    if (!self.faceView.isCompleted) {
        [self uploadClick:1];
        return;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showImage:(UIImage *)image {
    if (self.photoIndex == 0) {
        self.photoImage = image;
    }else if (self.photoIndex == 1) {
        self.faceImage = image;
    }
}

- (void)refreshData {
    NSDictionary *dic = @{
        @"accommodate" : self.cardId
    };
    [XQHUD showLoadingInView:self.view];
    @weakify(self)
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/telex"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if ([responseObject[@"concept"] integerValue] == 0) {
            [self pageStatus:YES];
            [self setData:responseObject[@"accomplish"]];
        }else {
            [self pageStatus:NO];
        }
    }];
}

- (void)pageStatus:(BOOL)show{
    self.scrollView.hidden = !show;
    self.mainView.hidden = !show;
}

- (void)setData:(NSDictionary *)dic {    
    [self.photoView setTitle:dic[@"id_front_msg"]];
    [self.faceView setTitle:dic[@"face_msg"]];
    
    self.preferredDataSource = dic[@"esa"];
    self.alternativeDataSource = dic[@"european"];
    
    
    NSDictionary *issue = dic[@"issue"];
    [self.photoView setPhotoImageName:issue[@"aviation"]];
    [self.photoView setIsCompleted:[issue[@"evasive"] integerValue] == 1];
    
    NSDictionary *avoidance = dic[@"avoidance"];
    [self.faceView setPhotoImageName:avoidance[@"aviation"]];
    [self.faceView setIsCompleted:[avoidance[@"evasive"] integerValue] == 1];
}

- (void)saveUserInfo:(NSDictionary *)dic maneuvers:(NSString *)maneuvers startTime:(long long)startTime longitude:(CGFloat)longitude latitude:(CGFloat)latitude{
    
    if (maneuvers.length == 0) {
        [self refreshData];
        [self reportRisk:@"4" startTime:startTime longitude:longitude latitude:latitude];
        return;
    }
    
    XQAccureIdentityInfoPop *popView = [[XQAccureIdentityInfoPop alloc] init];
    
    self.selectName = dic[@"chance"];
    self.selectNumer = dic[@"did"];
    self.selectBirthday = [NSString stringWithFormat:@"%@/%@/%@",dic[@"kessler"],dic[@"phenomenon"],dic[@"cascade"]];
    self.maneuvers = maneuvers;
    
    [popView setTip:dic[@"triggering"]];
    [popView setDataSource:dic[@"potentially"]];
    
    @weakify(self);
    @weakify(popView);
    popView.birthdayHandle = ^{
        @strongify(self);
        @strongify(popView);
        [self birthdayShow:self.selectBirthday popView:popView];
    };
    popView.bgHandle = ^{
        @strongify(self);
        [self.view endEditing:YES];
    };
    popView.textFieldNameHandle = ^(NSString * _Nonnull text) {
        @strongify(self);
        self.selectName = text;
    };
        
    popView.textFieldNumberHandle = ^(NSString * _Nonnull text) {
        @strongify(self);
        self.selectNumer = text;
    };
    
    XQPopupAnimView *anim = [[XQPopupAnimView alloc] initWithAnimationType:XQPopupAnimationCenter customView:popView];
    anim.needCover = YES;
    anim.canClickOutside = YES;
    anim.makeCustomConstraints = ^(XQPopupAnimView *animView, UIView *customView) {
        [customView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.offset(0.f);
        }];
    };
    
    [anim showInView:self.view completion:^{}];
    
    @weakify(anim)
    popView.confimHandle = ^(BOOL isClose) {
        @strongify(anim);
        if (isClose) {
            [anim hideAndCompletion:^{}];
        }else {
            [self refreshPopData:anim startTime:startTime longitude:longitude latitude:latitude];
        }
    };
}

- (void)birthdayShow:(NSString *)day popView:(XQAccureIdentityInfoPop *)parentPopView {

    XQIdentityBirthdayPopView *popView = [[XQIdentityBirthdayPopView alloc] init];
    [popView setCurrentDate:day];

    XQPopupAnimView *anim = [[XQPopupAnimView alloc] initWithAnimationType:XQPopupAnimationCenter customView:popView];
    anim.needCover = YES;
    anim.makeCustomConstraints = ^(XQPopupAnimView *animView, UIView *customView) {
        [customView mas_remakeConstraints:^(MASConstraintMaker *make) {
            (void)make.center;
        }];
    };
    
    [anim showInView:self.view completion:^{}];
    
    @weakify(anim)
    popView.confimHandle = ^(NSString * _Nonnull day) {
        @strongify(anim);
        self.selectBirthday = day;
        [parentPopView setBirthday:day];
        [anim hideAndCompletion:^{}];
    };
}

- (void)refreshPopData:(XQPopupAnimView *)anim startTime:(long long)startTime longitude:(CGFloat)longitude latitude:(CGFloat)latitude{
    NSMutableDictionary *dic = @{
        @"syndrome" : self.selectBirthday,
        @"did" : self.selectNumer,
        @"chance" : self.selectName,
    }.mutableCopy;
    
    if (self.maneuvers.length) {
        [dic setValue:@"11" forKey:@"spacemobile"];
        [dic setValue:self.maneuvers forKey:@"maneuvers"];
    }else {
        [dic setValue:@"10" forKey:@"spacemobile"];
    }
    
    [XQHUD showLoadingInView:self.view];
    @weakify(self)
    [XQAFNetworking postWithUrl:[XQNetManager getAbsolutePath:@"/direct/nautical"] pars:dic callback:^(_Bool success, id  _Nonnull responseObject, NSError * _Nonnull error) {
        @strongify(self);
        [XQHUD hideLoadindInView:self.view];
        if ([responseObject[@"concept"] integerValue] == 0) {
            [anim hideAndCompletion:^{}];
            
            [XQToolManager manager].userName = self.selectName;
            
            [self refreshData];
            
            [self reportRisk:@"3" startTime:startTime longitude:longitude latitude:latitude];
        }else {
            [XQToast showMsg:responseObject[@"loon"]];
        }
    }];
}

- (void)reportRisk:(NSString *)type startTime:(long long)startTime longitude:(CGFloat)longitude latitude:(CGFloat)latitude{
    [XQGoogleMarket reportRiskWithType:type longitude:longitude latitude:latitude startTime:startTime endTime:[XQTimeTool nowTimeStamp] orderId:@""];
}

#pragma mark - lazy

- (UIView *)mainView {
    if (!_mainView) {
        _mainView = [[UIView alloc] init];
        _mainView.hidden = YES;
    }
    return _mainView;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.hidden = YES;
    }
    return  _scrollView;
}

- (XQCustomEngeLabel *)topLabel {
    if (!_topLabel) {
        _topLabel = [XQCustomEngeLabel new];
        _topLabel.text = @"Please fill in your personal data (don't \nworry,your information and data are \nprotected)";
        _topLabel.edgtInsets = UIEdgeInsetsMake(12, 6, 12, 6);
        _topLabel.numberOfLines = 0;
        _topLabel.textColor = [UIColor whiteColor];
        _topLabel.font = [UIFont systemFontOfSize:16];
        _topLabel.backgroundColor = kOrangeColor;
        _topLabel.layer.cornerRadius = 15;
        _topLabel.layer.masksToBounds = YES;
        _topLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _topLabel;
}

- (XQIdentityPhotoView *)photoView {
    if (!_photoView) {
        _photoView = [XQIdentityPhotoView new];
        [_photoView setTitle:@"ID Card Front Photo"];
        [_photoView setDefaultImageName:@"photo_bg"];
        @weakify(self)
        _photoView.uploadHandle = ^{
            @strongify(self);
            [self uploadClick:0];
        };
    }
    return _photoView;
}

- (XQIdentityPhotoView *)faceView {
    if (!_faceView) {
        _faceView =[XQIdentityPhotoView new];
        [_faceView setTitle:@"Face Recognition"];
        [_faceView setDefaultImageName:@"face_bg"];
        @weakify(self)
        _faceView.uploadHandle = ^{
            @strongify(self);
            if (!self.photoView.isCompleted) {
                [XQToast showMsg:@"Please upload a photo of your identification document first"];
                return;
            }
            [self uploadClick:1];
        };
    }
    return _faceView;
}

- (XQButton *)bottomButton {
    if (!_bottomButton) {
        _bottomButton = [[XQButton alloc] initWithTitle:@"Next"];
        @weakify(self);
        _bottomButton.onTapHandle = ^{
            @strongify(self);
            [self bottomClick];
        };
    }
    return _bottomButton;
}


@end
